class AudioPlayer {
  constructor() {
    this.context = ''
    this.onCanPlay = {}
    this.onPlay = {}
    this.onTimeUpdate = {}
    this.onPause = {}
    this.onEnded = {}
    this.onError = {}
  }

  init() {
    this.context = document.createElement('audio')
    const events = ['onCanPlay', 'onPlay', 'onTimeUpdate', 'onPause', 'onEnded', 'onError']

    events.forEach((event) => {
      this.context.addEventListener(event.replace('on', '').toLocaleLowerCase(), (e) => {
        for (let key in this[event]) {
          this[event][key]()
        }
      })
    })
  }

  on(type, key, fn) {
    if (!type || !fn) return

    const event = this[type]
    if (!event || typeof event != 'object') return

    event[key] = fn
  }
  off(type, key) {
    if (!type || !key) return

    const event = this[type]
    if (!event || typeof event != 'object') return

    delete event[key]
  }

  play() {
    if (!this.context || this.onTimeUpdate.length === 0) return

    this.context.play()
  }

  pause() {
    if (!this.context) return

    this.context.pause()
  }

  stop() {
    if (!this.context) return

    this.context.pause()
    this.context.currentTime = 0
  }
}

export default AudioPlayer
